package dao

import "time"

type Scene struct {
	Sc_id	int	`gorm:"primary_key" json:"sc_id"` //主键
	Uid int `json:"uid"`
	Nodes	string	`json:"nodes"` //
	Edges	string	`json:"edges"` //
	Num	uint8	`json:"num"` //
	Scene_name	string	`json:"scene_name"` //场景名称
	Scene_difficulty	string	`json:"scene_difficulty"` //场景难度
	Scene_desc	string	`json:"scene_desc"` //场景描述
	Dynamic_tag	string	`json:"dynamic_tag"` //场景标签
	Img_url	string	`json:"img_url"` //图片地址
	C_time	int64	`json:"c_time"` //创建时间
	D_time	int64	`json:"d_time"` //删除时间
}

type Scenes struct {
	Sc_id	int	`gorm:"primary_key" json:"sc_id"` //主键
	Uid int `json:"uid"`
	Num	uint8	`json:"num"` //
	Scene_name	string	`json:"scene_name"` //场景名称
	Scene_difficulty	string	`json:"scene_difficulty"` //场景难度
	Scene_desc	string	`json:"scene_desc"` //场景描述
	Dynamic_tag	string	`json:"dynamic_tag"` //场景标签
	Username	string	`json:"username"` //用户名称
	Img_url	string	`json:"img_url"` //图片地址
	C_time	int64	`json:"c_time"` //创建时间
}


type sceneAndNode struct {
	Scene
	SceneNode []SceneNode `json:"scene_node"`
}

func (e *Scene) Create() (id int, err error) {
	result := db.Create(&e)
	if result.Error != nil {
		err = result.Error
		return
	}
	id = e.Sc_id
	return
}

func (e *Scenes) GetPage(pageSize int, pageIndex int) ([]Scenes, int, error) {
	var doc []Scenes

	table := db.Select("*").Where("bc_scene.d_time = 0")
	if e.Num != 0 {
		table = table.Where("num = ?", e.Num)
	}
	if e.Uid != 0 {
		table = table.Where("uid = ?", e.Uid)
	}
	if e.Scene_name != "" {
		table = table.Where("scene_name like ?", "%" + e.Scene_name + "%")
	}
	if e.Scene_difficulty != "" {
		table = table.Where("scene_difficulty like ?", e.Scene_difficulty)
	}

	var count int

	if err := table.Table("bc_scene").Select("sc_id,bc_scene.uid,num,scene_name," +
		"scene_difficulty,scene_desc,dynamic_tag,username,img_url,bc_scene.c_time").
		Joins("left join bc_user as user on bc_scene.uid=user.uid").Order("sc_id desc").
		Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Table("bc_scene").Count(&count)
	return doc, count, nil
}

func (e Scene) Get()(sceneAndNode,error)  {
	table := db.Select("*")
	if e.Sc_id != 0 {
		table = table.Where("sc_id = ?", e.Sc_id)
	}
	if err := table.First(&e).Error; err != nil {
		return sceneAndNode{},err
	}
	node := SceneNode{Scene_id: e.Sc_id}
	nodes,_ := node.Find()

	return sceneAndNode{e,nodes},nil
}

func (e Scene) Delete() error  {
	table := db.Table("bc_scene").Select("*")
	if e.Sc_id != 0 {
		table = table.Where("sc_id = ?", e.Sc_id)
	}
	if err := table.Update("d_time",time.Now().Unix()).Error; err != nil {
		return err
	}
	return nil
}
